//
//  HQWKViewController.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//
#import "THWKWebViewController.h"
#import "THWKWebView.h"
#import "THWebViewModel.h"
//#import "UIScrollView+MJRefresh.h"
#import "THWebProgressLayer.h"

@interface THWKWebViewController ()<WKNavigationDelegate>

@property (nonatomic, retain)    THWebViewModel *viewModel;
@property (nonatomic, retain)    THWKWebView *webView;
@property (nonatomic, strong)    UIButton * backBtn;
//@property (nonatomic, strong)    MJRefreshHeader* mj_header;

@property(nonatomic, strong)    NSURL *webUrl;            //weburl

@property (nonatomic, strong) UIBarButtonItem         *closeBarButton;
@property (nonatomic, strong) UIBarButtonItem         *backBarButton;

@property (nonatomic, strong) UIButton                 *closeButton;

@property (copy,nonatomic) NSString * currentURL;

@property (nonatomic, strong) THWebProgressLayer *layer;

//自定义头像的导航栏,因为  有的h5界面 ，透明的导航栏遮挡住了h5的点击事件，因此此view仅作为其他空间设置约束的参考
@property (nonatomic, strong) UIView *clearNav;

@property (nonatomic, strong) UIButton *clearBackBtn;

@property (nonatomic, strong) UIButton *clearCloseBtn;

@end

@implementation THWKWebViewController
@dynamic viewModel;
- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    self.clearNav.hidden = !self.viewModel.hidenNavigationBar;
    
    self.clearBackBtn.hidden = !self.viewModel.hidenNavigationBar;
    self.clearCloseBtn.hidden = !self.viewModel.hidenNavigationBar;
}

- (void)configViews{
    [super configViews];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self loadData];
}

/**子类添加控件 */
- (void)setupUI{
    [self layoutWebView];
    
    NSMutableArray * array = @[].mutableCopy;//[self.navigationItem.leftBarButtonItems mutableCopy];
    [array addObject:self.backBarButton];
    [array addObject:self.closeBarButton];
    [self setNavLeftButtonWithClose:NO];
    [self.navigationItem setLeftBarButtonItems:array];
    [self.webView setAllowsBackForwardNavigationGestures:YES];
    [self.webView.layer addSublayer:self.layer];
    
    [self.view addSubview:self.clearNav];
    [self.clearNav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(0);
        make.height.equalTo(kStatusBarHeight + 44);
    }];
    
    [self.view addSubview:self.clearBackBtn];
    [self.clearBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.size.equalTo(24);
        make.bottom.equalTo(self.clearNav).offset(-10);
    }];
    
    [self.view addSubview:self.clearCloseBtn];
    [self.clearCloseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.clearBackBtn);
        make.left.equalTo(44);
        make.size.equalTo(24);
    }];
}

- (void)loadData
{
    [self.webView loadRequest:[NSURLRequest requestWithURL:[self.viewModel.urlString appendTimeUrl].kURL]];
    self.currentURL = self.viewModel.urlString;
}

- (void)layoutWebView
{
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}


- (void)reloadWebViewForUrlForV2
{
    if(self.webView.request.URL == nil)
    {
        if([self.webUrl absoluteString].length >0)
        {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.webUrl];
            [self.webView loadRequest:request];
        }
    }
    else
    {
        [self.webView reload];
    }
}

- (void)setWebUrl:(NSURL *)webUrl
{
    if ([webUrl isKindOfClass:[NSString class]])
    {
        _webUrl = [(NSString *)webUrl kURL];
    }
    else
    {
        _webUrl = webUrl;
    }
}

- (void)goBack
{
    if ([self.webView canGoBack]) {
        self.closeButton.hidden = NO;
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)setNavLeftButtonWithClose:(BOOL)showClose
{
    self.closeButton.hidden = !showClose;
}

- (void)closeAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*刷新*/
- (void)refresh
{
    [self.webView reload];
    [self refreshTitle];
}

/*前进*/
- (void)goForward
{
    if([self.webView canGoForward])
    {
        [self refreshTitle];
        [self.webView goForward];
    }
}

/*后退*/
- (void)webGoBack
{
    if([self.webView canGoBack])
    {
        [self refreshTitle];
        [self.webView goBack];
    }
}


/*刷新标题*/
- (NSString*)refreshTitle
{
    @weakify(self)
    [self.webView evaluateJavaScript:@"document.title" completionHandler:^(NSString * result, NSError *error) {
        @strongify(self)
        NSString * title = (result.length > 0)? result : self.title;
        
        NSString *str = [NSString stringWithFormat:@"%@",@"就"];
        str = [str stringByAppendingString:@"聊"];
        if (title.length > 0 && [title containsString:str]) {
            title = [title stringByReplacingOccurrencesOfString:str withString:KAPPName];
        }
        
        [self.navigationItem setTitle:title];
        if (title.length == 0)
        {
            [self performSelector:@selector(refreshTitleAgain) withObject:nil afterDelay:1];
        }
    }];
    return self.navigationItem.title;
}

//容错重试一次
- (void)refreshTitleAgain
{
    @weakify(self)
    [self.webView evaluateJavaScript:@"document.title" completionHandler:^(NSString * result, NSError *error) {
        @strongify(self)
        NSString * title = (result.length > 0)? result : self.title;
        [self.navigationItem setTitle:title];
    }];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURLRequest *request = navigationAction.request;
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated ) {//新开页面
//        TODO:是否需要新开页面
    }else{
        _currentURL = request.mainDocumentURL.absoluteString;
    }
    [self.layer startLoad];
    decisionHandler(WKNavigationActionPolicyAllow);

}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    //刷新标题
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self refreshTitle];
    });
    
//    [self.mj_header endRefreshing];
    [self.layer finishedLoad];

}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
//    TODO:错误页面记载处理
    
}


//- (MJRefreshHeader*)mj_header{
//    if (!_mj_header) {
//        MJRefreshStateHeader *mj_header = [[MJRefreshStateHeader alloc] init];
//        [mj_header setTitle:@"正在加载中,请稍后..." forState:MJRefreshStateRefreshing];
//        [mj_header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
//        mj_header.lastUpdatedTimeLabel.hidden = YES;//将时间隐藏
//        @weakify(self);
//        [mj_header setRefreshingBlock:^{
//            @strongify(self);
//            [self refresh];
//        }];
//        _mj_header = mj_header;
//    }
//
//    return _mj_header;
//}

- (THWKWebView *)webView
{
    if (!_webView) {
        _webView = [THWKWebView getInstance];
        _webView.clipsToBounds = YES;
        _webView.delegate = self;
        _webView.opaque = NO;
//        _webView.scrollView.mj_header = self.mj_header;
    }
    return _webView;
}

- (UIBarButtonItem *)closeBarButton
{
    if (!_closeBarButton) {
        _closeBarButton = [[UIBarButtonItem alloc]initWithCustomView:self.closeButton];
    }
    return _closeBarButton;;
}

- (UIBarButtonItem *)backBarButton
{
    if (!_backBarButton) {
        self.backBtn.frame           = CGRectMake(0, 0, 30, 30);
        _backBarButton = [[UIBarButtonItem alloc]initWithCustomView:self.backBtn];
    }
    return _backBarButton;
}

- (UIButton *)backBtn
{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setImage:[UIImage imageNamed:@"baseImg_back_black_big"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;;
}

- (UIButton *)closeButton
{
    if (!_closeButton) {
        _closeButton     = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton setBackgroundColor:[UIColor clearColor]];
        _closeButton.exclusiveTouch  = YES;
        _closeButton.frame           = CGRectMake(0, 0, 30, 30);
        [_closeButton setImage:[UIImage imageNamed:@"baseImg_close_black"] forState:UIControlStateNormal];
        [_closeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}

-(THWebProgressLayer *)layer
{
    if (!_layer) {
        _layer = THWebProgressLayer.new;
    }
    return _layer;
}

-(UIView *)clearNav
{
    if (!_clearNav) {
        _clearNav = UIView.new;
        _clearNav.backgroundColor = [UIColor clearColor];
        _clearNav.hidden = YES;
    }
    return _clearNav;
}

-(UIButton *)clearCloseBtn
{
    if (!_clearCloseBtn) {
        _clearCloseBtn     = [UIButton buttonWithType:UIButtonTypeCustom];
        [_clearCloseBtn setBackgroundColor:[UIColor clearColor]];
        _clearCloseBtn.exclusiveTouch  = YES;
        _clearCloseBtn.frame           = CGRectMake(0, 0, 30, 30);
        [_clearCloseBtn setImage:[UIImage imageNamed:@"baseImg_web_close"] forState:UIControlStateNormal];
        [_clearCloseBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_clearCloseBtn addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _clearCloseBtn;
}

- (UIButton *)clearBackBtn
{
    if (!_clearBackBtn) {
        _clearBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_clearBackBtn setImage:[UIImage imageNamed:@"baseImg_web_back"] forState:UIControlStateNormal];
        [_clearBackBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clearBackBtn;;
}


@end
